package com.example.gitclient.adapter;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.gitclient.R;
import com.example.gitclient.model.Repository;

import java.util.List;

/**
 * 仓库列表适配器
 */
public class RepositoryAdapter extends RecyclerView.Adapter<RepositoryAdapter.ViewHolder> {
    private final List<Repository> repositories;
    private final OnRepositoryClickListener listener;

    /**
     * 仓库点击监听器接口
     */
    public interface OnRepositoryClickListener {
        void onRepositoryClick(Repository repository);
    }

    /**
     * 创建仓库列表适配器
     * @param repositories 仓库列表
     * @param listener 点击监听器
     */
    public RepositoryAdapter(List<Repository> repositories, OnRepositoryClickListener listener) {
        this.repositories = repositories;
        this.listener = listener;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return new ViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_repository, parent, false));
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        Repository repository = repositories.get(position);
        holder.tvRepositoryName.setText(repository.getName());
        holder.tvRepositoryPath.setText(repository.getPath());
        
        String currentBranch = repository.getCurrentBranch();
        if (currentBranch != null && !currentBranch.isEmpty()) {
            holder.tvCurrentBranch.setText("分支: " + currentBranch);
            holder.tvCurrentBranch.setVisibility(View.VISIBLE);
        } else {
            holder.tvCurrentBranch.setVisibility(View.GONE);
        }

        holder.btnOpenRepository.setOnClickListener(v -> {
            if (listener != null) {
                listener.onRepositoryClick(repository);
            }
        });
    }

    @Override
    public int getItemCount() {
        return repositories.size();
    }

    /**
     * 视图持有者
     */
    public static class ViewHolder extends RecyclerView.ViewHolder {
        TextView tvRepositoryName;
        TextView tvRepositoryPath;
        TextView tvCurrentBranch;
        Button btnOpenRepository;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            tvRepositoryName = itemView.findViewById(R.id.tvRepositoryName);
            tvRepositoryPath = itemView.findViewById(R.id.tvRepositoryPath);
            tvCurrentBranch = itemView.findViewById(R.id.tvCurrentBranch);
            btnOpenRepository = itemView.findViewById(R.id.btnOpenRepository);
        }
    }
}